<template>
  <div class="admin-page admin-course">
    <div class="page-header">
      <h1>课程管理</h1>
      <div class="actions">
        <el-button type="success" @click="downloadTemplate">
          <el-icon><Download /></el-icon> 下载模板
        </el-button>
        <el-button type="warning" @click="openImportDialog">
          <el-icon><Upload /></el-icon> 批量导入
        </el-button>
        <el-button type="primary" @click="openCourseDialog(null)">
          <el-icon><Plus /></el-icon> 新增课程
        </el-button>
      </div>
    </div>
    
    <el-card class="table-card">
      <div class="filter-container">
        <el-form :inline="true" class="filter-form">
          <el-form-item label="课程名称">
            <el-input v-model="filters.name" placeholder="请输入课程名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="课程代码">
            <el-input v-model="filters.code" placeholder="请输入课程代码" clearable></el-input>
          </el-form-item>
          <el-form-item label="单位">
            <el-select v-model="filters.departmentId" placeholder="请选择单位" clearable>
              <el-option 
                v-for="dept in departments" 
                :key="dept.id" 
                :label="dept.name" 
                :value="dept.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="培养层次">
            <el-select v-model="filters.cengciId" placeholder="请选择培养层次" clearable>
              <el-option 
                v-for="cengci in cengcis" 
                :key="cengci.id" 
                :label="cengci.name" 
                :value="cengci.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="专业">
            <el-select v-model="filters.majorId" placeholder="请选择专业" clearable>
              <el-option 
                v-for="major in majors" 
                :key="major.id" 
                :label="major.name" 
                :value="major.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchCourses">搜索</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <el-table
        v-loading="loading"
        :data="filteredCourses"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="课程ID" width="100" resizable></el-table-column>
        <el-table-column prop="name" label="课程名称" min-width="120" resizable></el-table-column>
        <el-table-column prop="code" label="课程代码" min-width="120" resizable></el-table-column>
        <el-table-column prop="totalHours" label="课时" width="80" resizable>
          <template #default="scope">
            {{ scope.row.totalHours || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="departmentNames" label="教研室" min-width="120" resizable>
          <template #default="scope">
            <div v-if="scope.row.departmentNames && scope.row.departmentNames.length">
              <el-tag v-for="(deptName, index) in scope.row.departmentNames" :key="index" size="small" style="margin-right: 5px; margin-bottom: 5px;">
                {{ deptName }}
              </el-tag>
            </div>
            <span v-else>无部门</span>
          </template>
        </el-table-column>
        <el-table-column prop="cengCiNames" label="培养层次" min-width="120" resizable>
          <template #default="scope">
            <div v-if="scope.row.cengCiNames && scope.row.cengCiNames.length">
              <el-tag v-for="(cengCiName, index) in scope.row.cengCiNames" :key="index" size="small" type="warning" style="margin-right: 5px; margin-bottom: 5px;">
                {{ cengCiName }}
              </el-tag>
            </div>
            <span v-else>无层次</span>
          </template>
        </el-table-column>
        <el-table-column prop="majorNames" label="专业" min-width="120" resizable>
          <template #default="scope">
            <div v-if="scope.row.majorNames && scope.row.majorNames.length">
              <el-tag v-for="(majorName, index) in scope.row.majorNames" :key="index" size="small" type="success" style="margin-right: 5px; margin-bottom: 5px;">
                {{ majorName }}
              </el-tag>
            </div>
            <span v-else>无专业</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="课程描述" min-width="180" resizable>
          <template #default="scope">
            <el-tooltip 
              class="box-item" 
              effect="dark" 
              :content="scope.row.description || '无描述'" 
              placement="top-start"
              :hide-after="2000"
            >
              <div class="truncate-text">{{ scope.row.description || '无描述' }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200" resizable>
          <template #default="scope">
            <el-button size="small" type="primary" @click="openCourseDialog(scope.row)">
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteCourse(scope.row)">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 课程编辑对话框 -->
    <el-dialog
      :title="isEdit ? '编辑课程' : '新增课程'"
      v-model="dialogVisible"
      width="500px"
      append-to-body
      @close="handleDialogClose"
    >
      <el-form :model="courseForm" :rules="rules" ref="courseFormRef" label-width="80px">
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="courseForm.name" placeholder="请输入课程名称"></el-input>
        </el-form-item>
        <el-form-item label="课程代码" prop="code">
          <el-input v-model="courseForm.code" placeholder="请输入课程代码"></el-input>
        </el-form-item>
        <el-form-item label="教研室" prop="departmentIds">
          <el-select v-model="courseForm.departmentIds" multiple placeholder="请选择教研室">
            <el-option 
              v-for="dept in researchOffices" 
              :key="dept.id" 
              :label="dept.name" 
              :value="dept.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="培养层次" prop="cengCiIds">
          <el-select v-model="courseForm.cengCiIds" multiple placeholder="请选择培养层次">
            <el-option 
              v-for="cengci in cengcis" 
              :key="cengci.id" 
              :label="cengci.name" 
              :value="cengci.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专业" prop="majorIds">
          <el-select v-model="courseForm.majorIds" multiple placeholder="请选择专业">
            <el-option 
              v-for="major in majors" 
              :key="major.id" 
              :label="major.name" 
              :value="major.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程描述" prop="description">
          <el-input type="textarea" v-model="courseForm.description" placeholder="请输入课程描述" :rows="3"></el-input>
        </el-form-item>
        <el-form-item label="课时" prop="totalHours">
          <el-input-number 
            v-model="courseForm.totalHours" 
            :min="0" 
            :max="999"
            :step="1" 
            controls-position="right"
            style="width: 120px;">
          </el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCourseForm" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="批量导入课程"
      width="50%"
      :close-on-click-modal="false"
    >
      <div class="import-content">
        <el-alert
          title="导入说明"
          type="info"
          :closable="false"
          show-icon
        >
          <template #default>
            <p>1. 请先下载模板文件，按照模板格式填写课程信息</p>
            <p>2. <span style="color: red; font-weight: bold;">必填字段</span>：课程名称、课程代码</p>
            <p>3. <span style="color: green; font-weight: bold;">可选字段</span>：课程描述、课程类型、考核方式、开课单位、专业、培养层次、课时、课程状态</p>
            <p>4. 课程代码必须在系统中唯一</p>
            <p>5. 课程类型可选：必修、选修、其他</p>
            <p>6. 考核方式可选：考试、考查</p>
            <p>7. 课程状态可选：启用、停用、其他，默认为启用</p>
            <p>8. 开课单位、专业、培养层次支持多个，用逗号分隔</p>
            <p>9. 如有数据错误，将不会保存任何数据，请修正后重新导入</p>
          </template>
        </el-alert>

        <el-upload
          ref="uploadRef"
          class="upload-area"
          drag
          :auto-upload="false"
          :on-change="handleFileChange"
          :file-list="fileList"
          accept=".xlsx,.xls"
          :limit="1"
        >
          <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传 Excel 文件，且文件大小不超过 10MB
            </div>
          </template>
        </el-upload>

        <div v-if="importResult" class="import-result">
          <el-alert
            :title="importResult.message"
            :type="importResult.success ? 'success' : 'error'"
            :closable="false"
            show-icon
          >
            <template #default>
              <p v-if="importResult.success">
                成功导入 {{ importResult.data?.successCount || 0 }} 条课程记录
              </p>
              <p v-if="importResult.data?.failureCount > 0">
                失败 {{ importResult.data.failureCount }} 条记录
              </p>
              <div v-if="importResult.data?.errors?.length > 0" class="error-details">
                <p><strong>错误详情：</strong></p>
                <div class="error-content">
                  <div v-for="(error, index) in importResult.data.errors" :key="index" class="error-item">
                    <pre>{{ error }}</pre>
                  </div>
                </div>
              </div>
            </template>
          </el-alert>
        </div>
      </div>

      <template #footer>
        <el-button @click="cancelImport">取消</el-button>
        <el-button type="primary" @click="handleImport" :loading="importing" :disabled="!selectedFile">
          导入
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed, reactive, nextTick } from "vue";
import { courseApi, downloadCourseTemplate, importCourses } from "@/api/base-data";
import { departmentApi } from "@/api/base-data";
import { cengCiApi } from "@/api/base-data";
import { majorApi } from "@/api/base-data";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Edit, Delete, Download, Upload, UploadFilled } from "@element-plus/icons-vue";

export default {
  components: {
    Plus,
    Edit,
    Delete,
    Download,
    Upload,
    UploadFilled
  },
  setup() {
    const courses = ref([]);
    const departments = ref([]);
    const researchOffices = ref([]); // 教研室列表
    const cengcis = ref([]); // 专业层次列表
    const majors = ref([]); // 专业列表
    const loading = ref(false);
    const submitting = ref(false);
    const dialogVisible = ref(false);
    const courseFormRef = ref(null);
    
    // 导入相关
    const importDialogVisible = ref(false);
    const importing = ref(false);
    const fileList = ref([]);
    const selectedFile = ref(null);
    const importResult = ref(null);
    const uploadRef = ref(null);
    
    // 分页相关
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    
    // 筛选条件
    const filters = reactive({
      name: "",
      code: "",
      departmentId: "",
      cengciId: "",
      majorId: ""
    });
    
    // 课程表单
    const courseForm = reactive({
      id: "",
      name: "",
      code: "",
      description: "",
      departmentIds: [], // 使用与后端DTO一致的字段名
      cengCiIds: [], // 专业层次ID列表
      majorIds: [], // 专业ID列表
      totalHours: 0            // 课时字段
    });
    
    const isEdit = computed(() => !!courseForm.id);
    
    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: "请输入课程名称", trigger: "blur" }
      ],
      code: [
        { required: true, message: "请输入课程代码", trigger: "blur" }
      ],
      departmentId: [
        { required: false, message: "请选择所属部门", trigger: "change" }
      ],
      departmentIds: [
        { required: true, message: "请选择所属部门", trigger: "change" }
      ]
    };

    const fetchCourses = async () => {
      loading.value = true;
      try {
        courses.value = await courseApi.getAllCourses();
        total.value = courses.value.length;
      } catch (error) {
        ElMessage.error("获取课程列表失败");
      } finally {
        loading.value = false;
      }
    };
    
    const fetchDepartments = async () => {
      try {
        // 获取所有部门用于过滤
        departments.value = await departmentApi.getAllDepartments();
        // 获取教研室用于编辑对话框
        researchOffices.value = await departmentApi.getResearchOffices();
      } catch (error) {
        ElMessage.error("获取部门列表失败");
      }
    };
    
    const fetchCengCis = async () => {
      try {
        cengcis.value = await cengCiApi.getAllCengCi();
      } catch (error) {
        ElMessage.error("获取专业层次列表失败");
      }
    };
    
    const fetchMajors = async () => {
      try {
        majors.value = await majorApi.getAllMajors();
      } catch (error) {
        ElMessage.error("获取专业列表失败");
      }
    };
    
    // 根据筛选条件过滤数据
    const filteredCourses = computed(() => {
      let filtered = courses.value;
      
      if (filters.name) {
        filtered = filtered.filter(course => 
          course.name.includes(filters.name)
        );
      }
      
      if (filters.code) {
        filtered = filtered.filter(course => 
          course.code.includes(filters.code)
        );
      }
      
      if (filters.departmentId) {
        filtered = filtered.filter(course => 
          course.departmentIds && course.departmentIds.includes(filters.departmentId)
        );
      }
      
      if (filters.cengciId) {
        filtered = filtered.filter(course => 
          course.cengCiIds && course.cengCiIds.includes(filters.cengciId)
        );
      }
      
      if (filters.majorId) {
        filtered = filtered.filter(course => 
          course.majorIds && course.majorIds.includes(filters.majorId)
        );
      }
      
      // 更新总数
      total.value = filtered.length;
      
      // 返回当前页的数据
      const startIndex = (currentPage.value - 1) * pageSize.value;
      return filtered.slice(startIndex, startIndex + pageSize.value);
    });
    
    // 搜索课程
    const searchCourses = () => {
      currentPage.value = 1;
    };
    
    // 重置筛选条件
    const resetFilters = () => {
      filters.name = "";
      filters.code = "";
      filters.departmentId = "";
      filters.cengciId = "";
      filters.majorId = "";
      currentPage.value = 1;
    };
    
    // 处理页码变化
    const handlePageChange = (page) => {
      currentPage.value = page;
    };
    
    // 打开课程编辑对话框
    const openCourseDialog = async (course) => {
      // 总是先强制重置表单
      forceResetCourseForm();
      
      if (course) {
        // 编辑模式：填充现有数据
        courseForm.id = course.id;
        courseForm.name = course.name;
        courseForm.code = course.code;
        courseForm.departmentIds = course.departmentIds || [];
        courseForm.cengCiIds = course.cengCiIds || [];
        courseForm.majorIds = course.majorIds || [];
        courseForm.description = course.description || "";
        courseForm.totalHours = course.totalHours || 0;
      }
      
      dialogVisible.value = true;
      
      // 使用 nextTick 确保对话框完全渲染后再清除验证状态
      await nextTick();
      if (courseFormRef.value) {
        courseFormRef.value.clearValidate();
      }
    };
    
    // 强制重置课程表单
    const forceResetCourseForm = () => {
      courseForm.id = "";
      courseForm.name = "";
      courseForm.code = "";
      courseForm.departmentIds = [];
      courseForm.cengCiIds = [];
      courseForm.majorIds = [];
      courseForm.description = "";
      courseForm.totalHours = 0;
    };
    
    // 提交课程表单
    const submitCourseForm = async () => {
      if (!courseFormRef.value) return;
      
      try {
        await courseFormRef.value.validate();
        submitting.value = true;
        
        // 现在表单字段名与后端DTO一致，直接使用
        const formData = { ...courseForm };
        
        if (isEdit.value) {
          await courseApi.updateCourse(formData.id, formData);
          ElMessage.success("更新课程成功");
        } else {
          await courseApi.createCourse(formData);
          ElMessage.success("创建课程成功");
        }
        
        dialogVisible.value = false;
        fetchCourses();
      } catch (error) {
        ElMessage.error("操作失败: " + (error.message || "未知错误"));
      } finally {
        submitting.value = false;
      }
    };

    // 处理对话框关闭
    const handleDialogClose = async () => {
      // 对话框关闭时强制重置表单，确保下次打开时是干净的状态
      forceResetCourseForm();
      await nextTick();
      if (courseFormRef.value) {
        courseFormRef.value.clearValidate();
      }
    };

    // 删除课程
    const deleteCourse = async (course) => {
      try {
        await ElMessageBox.confirm(`确定要删除课程 ${course.name} 吗？`, "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        });
        
        await courseApi.deleteCourse(course.id);
        ElMessage.success("删除成功");
        fetchCourses();
      } catch (error) {
        if (error !== "cancel") {
          ElMessage.error(`删除课程失败: ${error.message || '未知错误'}`);
        }
      }
    };

    // 导入相关方法
    const openImportDialog = () => {
      importDialogVisible.value = true;
      importResult.value = null;
      fileList.value = [];
      selectedFile.value = null;
    };

    const handleFileChange = (file) => {
      selectedFile.value = file.raw;
      fileList.value = [file];
    };

    const handleImport = async () => {
      if (!selectedFile.value) {
        ElMessage.warning('请选择要导入的文件');
        return;
      }

      importing.value = true;
      importResult.value = null;

      try {
        const result = await importCourses(selectedFile.value);
        importResult.value = {
          success: true,
          message: '导入完成',
          data: result
        };
        
        if (result.successCount > 0) {
          // 导入成功后刷新列表
          await fetchCourses();
        }
      } catch (error) {
        let errorMessage = '未知错误';
        let errorDetails = [];
        
        if (error.response?.data) {
          const responseData = error.response.data;
          // 检查响应结构
          if (responseData.code && responseData.code !== 200) {
            // 错误响应
            errorMessage = responseData.message || '导入失败';
            if (responseData.data?.error) {
              // 详细错误信息在data.error中
              errorDetails = [responseData.data.error];
            } else {
              errorDetails = [errorMessage];
            }
          } else if (responseData.message) {
            // 旧格式兼容
            errorMessage = responseData.message;
            errorDetails = [responseData.message];
          }
        } else {
          errorMessage = error.message || '网络错误';
          errorDetails = [errorMessage];
        }
        
        
        importResult.value = {
          success: false,
          message: errorMessage,
          data: { errors: errorDetails }
        };
      } finally {
        importing.value = false;
      }
    };

    const cancelImport = () => {
      importDialogVisible.value = false;
      importResult.value = null;
      fileList.value = [];
      selectedFile.value = null;
      if (uploadRef.value) {
        uploadRef.value.clearFiles();
      }
    };

    const downloadTemplate = async () => {
      try {
        const response = await downloadCourseTemplate();
        
        // 获取blob数据 - 根据request.js的处理逻辑
        let blob;
        if (response instanceof Blob) {
          blob = response;
        } else if (response.data instanceof Blob) {
          blob = response.data;
        } else {
          ElMessage.error('下载失败：响应格式错误');
          return;
        }
        
        // 创建下载链接
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = 'course_import_template.xlsx';
        
        // 触发下载
        document.body.appendChild(link);
        link.click();
        
        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        
        ElMessage.success('模板下载成功');
      } catch (error) {
        ElMessage.error('下载模板失败');
      }
    };

    onMounted(async () => {
      await Promise.all([fetchCourses(), fetchDepartments(), fetchCengCis(), fetchMajors()]);
    });

    return {
      courses,
      filteredCourses,
      departments,
      researchOffices,
      cengcis,
      majors,
      loading,
      filters,
      currentPage,
      pageSize,
      total,
      courseForm,
      courseFormRef,
      rules,
      dialogVisible,
      submitting,
      isEdit,
      // 导入相关
      importDialogVisible,
      importing,
      fileList,
      selectedFile,
      importResult,
      uploadRef,
      // 方法
      searchCourses,
      resetFilters,
      handlePageChange,
      openCourseDialog,
      submitCourseForm,
      deleteCourse,
      handleDialogClose,
      forceResetCourseForm,
      // 导入相关方法
      openImportDialog,
      handleFileChange,
      handleImport,
      cancelImport,
      downloadTemplate
    };
  }
};
</script>

<style scoped>
.admin-course {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.actions {
  margin-left: auto;
}

.table-card {
  margin-bottom: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
}

:deep(.el-dialog__footer) {
  padding-top: 0;
}

.truncate-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 180px;
}

.import-content {
  margin-bottom: 20px;
}

.upload-area {
  margin: 20px 0;
}

.import-result {
  margin-top: 20px;
}

.error-details {
  margin-top: 10px;
}

.error-content {
  margin: 5px 0;
  max-height: 300px;
  overflow-y: auto;
}

.error-item {
  margin-bottom: 10px;
}

.error-item pre {
  background-color: #fef2f2;
  border: 1px solid #fecaca;
  border-radius: 4px;
  padding: 12px;
  margin: 0;
  white-space: pre-wrap;
  word-break: break-word;
  color: #dc2626;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  font-size: 13px;
  line-height: 1.5;
}
</style>
